import rpg_component from "../../../component/rpg_component";
import { TriggerCondition, TriggerConditionGroup, TriggerConditionConfig } from "../types";
import { ConditionType, ConditionOperator, Attribute_base } from "../../../shared/face/enums";

export class TriggerConditionParser {
  /**
   * 解析触发条件配置
   */
  static parseConditionConfig(
    config: TriggerConditionConfig,
    unit: rpg_component,
    allies: rpg_component[],
    opponents: rpg_component[],
    round: number
  ): boolean {
    if (!config || !config.groups || config.groups.length === 0) {
      return true; // 没有配置条件，默认触发
    }

    const groupResults = config.groups.map(group => this.evaluateConditionGroup(group, unit, allies, opponents, round));
    
    return config.logic === 'OR' 
      ? groupResults.some(result => result)
      : groupResults.every(result => result);
  }

  /**
   * 评估条件组
   */
  private static evaluateConditionGroup(
    group: TriggerConditionGroup,
    unit: rpg_component,
    allies: rpg_component[],
    opponents: rpg_component[],
    round: number
  ): boolean {
    const conditionResults = group.conditions.map(condition => 
      this.evaluateCondition(condition, unit, allies, opponents, round)
    );

    return group.logic === 'OR'
      ? conditionResults.some(result => result)
      : conditionResults.every(result => result);
  }

  /**
   * 评估单个条件
   */
  private static evaluateCondition(
    condition: TriggerCondition,
    unit: rpg_component,
    allies: rpg_component[],
    opponents: rpg_component[],
    round: number
  ): boolean {
    switch (condition.type) {
      case ConditionType.生命值百分比:
        return this.evaluateHealthPercentage(condition, unit);
      
      case ConditionType.生命值绝对值:
        return this.evaluateHealthAbsolute(condition, unit);
      
      case ConditionType.回合数:
        return this.evaluateRound(condition, round);
      
      case ConditionType.技能冷却:
        return this.evaluateSkillCooldown(condition, unit);
      
      case ConditionType.目标数量:
        return this.evaluateTargetCount(condition, allies, opponents);
      
      case ConditionType.自身状态:
        return this.evaluateSelfStatus(condition, unit);
      
      case ConditionType.敌方状态:
        return this.evaluateEnemyStatus(condition, opponents);
      
      case ConditionType.随机概率:
        return this.evaluateRandomProbability(condition);
      
      case ConditionType.属性值:
        return this.evaluateAttribute(condition, unit);
      
      case ConditionType.始终触发:
        return true;
      
      default:
        console.warn(`未知的触发条件类型: ${condition.type}`);
        return false;
    }
  }

  /**
   * 评估生命值百分比条件
   */
  private static evaluateHealthPercentage(condition: TriggerCondition, unit: rpg_component): boolean {
    const maxHp = unit.getAttribute(Attribute_base.最大生命值);
    const currentHp = unit.hp_now;
    const percentage = maxHp > 0 ? (currentHp / maxHp) * 100 : 0;
    
    return this.compareValues(percentage, condition.operator || ConditionOperator.大于, condition.value as number);
  }

  /**
   * 评估生命值绝对值条件
   */
  private static evaluateHealthAbsolute(condition: TriggerCondition, unit: rpg_component): boolean {
    return this.compareValues(unit.hp_now, condition.operator || ConditionOperator.大于, condition.value as number);
  }

  /**
   * 评估回合数条件
   */
  private static evaluateRound(condition: TriggerCondition, round: number): boolean {
    return this.compareValues(round, condition.operator || ConditionOperator.大于, condition.value as number);
  }

  /**
   * 评估技能冷却条件
   */
  private static evaluateSkillCooldown(condition: TriggerCondition, unit: rpg_component): boolean {
    if (!condition.skillId) return false;
    
    // 查找技能的冷却状态
    const skillData = unit.outSkills.find(skill => skill.skillId === condition.skillId);
    if (!skillData) return false;
    
    return this.compareValues(skillData.cooldown, condition.operator || ConditionOperator.等于, condition.value as number);
  }

  /**
   * 评估目标数量条件
   */
  private static evaluateTargetCount(condition: TriggerCondition, allies: rpg_component[], opponents: rpg_component[]): boolean {
    let count = 0;
    
    switch (condition.target) {
      case 'ally':
        count = allies.filter(unit => !unit.isDie()).length;
        break;
      case 'enemy':
        count = opponents.filter(unit => !unit.isDie()).length;
        break;
      case 'all':
        count = allies.filter(unit => !unit.isDie()).length + opponents.filter(unit => !unit.isDie()).length;
        break;
      default:
        count = opponents.filter(unit => !unit.isDie()).length;
    }
    
    return this.compareValues(count, condition.operator || ConditionOperator.大于, condition.value as number);
  }

  /**
   * 评估自身状态条件
   */
  private static evaluateSelfStatus(condition: TriggerCondition, unit: rpg_component): boolean {
    // 这里可以根据具体的状态值来判断
    // 例如：是否有特定buff、是否处于特定状态等
    const statusValue = this.getUnitStatusValue(unit, condition.value as string);
    return this.compareValues(statusValue, condition.operator || ConditionOperator.等于, 1);
  }

  /**
   * 评估敌方状态条件
   */
  private static evaluateEnemyStatus(condition: TriggerCondition, opponents: rpg_component[]): boolean {
    const aliveEnemies = opponents.filter(unit => !unit.isDie());
    if (aliveEnemies.length === 0) return false;
    
    // 检查是否有敌人满足特定状态
    const hasEnemyWithStatus = aliveEnemies.some(enemy => {
      const statusValue = this.getUnitStatusValue(enemy, condition.value as string);
      return this.compareValues(statusValue, condition.operator || ConditionOperator.等于, 1);
    });
    
    return hasEnemyWithStatus;
  }

  /**
   * 评估随机概率条件
   */
  private static evaluateRandomProbability(condition: TriggerCondition): boolean {
    const probability = condition.probability || condition.value as number;
    return Math.random() <= probability;
  }

  /**
   * 评估属性值条件
   */
  private static evaluateAttribute(condition: TriggerCondition, unit: rpg_component): boolean {
    if (!condition.attribute) return false;
    
    const attributeValue = unit.getAttribute(condition.attribute);
    return this.compareValues(attributeValue, condition.operator || ConditionOperator.大于, condition.value as number);
  }

  /**
   * 通用数值比较函数
   */
  private static compareValues(actual: number, operator: ConditionOperator, expected: number): boolean {
    switch (operator) {
      case ConditionOperator.大于:
        return actual > expected;
      case ConditionOperator.小于:
        return actual < expected;
      case ConditionOperator.等于:
        return actual === expected;
      case ConditionOperator.大于等于:
        return actual >= expected;
      case ConditionOperator.小于等于:
        return actual <= expected;
      case ConditionOperator.不等于:
        return actual !== expected;
      default:
        return false;
    }
  }

  /**
   * 获取单位状态值
   */
  private static getUnitStatusValue(unit: rpg_component, status: string): number {
    // 这里可以根据具体的状态类型来获取状态值
    // 例如：检查是否有特定buff、是否处于特定状态等
    switch (status) {
      case 'alive':
        return unit.isDie() ? 0 : 1;
      case 'hasBuff':
        return unit._activeBuffs.length > 0 ? 1 : 0;
      default:
        return 0;
    }
  }
} 